<template>
  <el-container class="product-list">
    <el-header>
      <h1>商品浏览</h1>
    </el-header>

    <el-main>
      <!-- 标签页切换 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- 所有商品标签 -->
        <el-tab-pane label="所有商品" name="all">
          <!-- 搜索框 -->
          <el-row justify="center" class="search-container">
            <el-col :span="12">
              <el-input
                  v-model="searchQuery"
                  placeholder="搜索商品..."
                  clearable
                  prefix-icon="el-icon-search"
              />
            </el-col>
          </el-row>

          <!-- 商品卡片列表 -->
          <el-row :gutter="20" class="products-list">
            <el-col v-for="product in filteredProducts" :key="product.id" :xs="24" :sm="12" :md="8">
              <el-card shadow="hover" class="product-card">
                <img :src="product.image_url" :alt="product.name" class="product-image" />
                <div class="product-info">
                  <h3>{{ product.name }}</h3>
                  <p>{{ product.description }}</p>
                  <div class="price-stock">
                    <span class="product-price">￥{{ product.price.toFixed(2) }}</span>
                    <el-tag type="info">库存: {{ product.stock }}</el-tag>
                  </div>
                </div>

                <div class="quantity-actions">
                  <el-input-number
                      v-model="product.quantity"
                      :min="1"
                      :max="999"
                      size="small"
                  />
                  <el-button v-if="role==='CUSTOMER'" type="primary" size="small" @click="addToCart(product)">
                    加入购物车
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- 推荐商品标签 - 仅对消费者显示 -->
        <el-tab-pane v-if="role==='CUSTOMER'" label="为您推荐" name="recommended">
          <!-- 推荐商品列表 -->
          <el-row :gutter="20" class="recommended-products">
            <el-col v-for="product in paginatedRecommendedProducts" :key="product.id" :xs="24" :sm="12" :md="8">
              <el-card shadow="hover" class="product-card">
                <img :src="product.image_url" :alt="product.name" class="product-image" />
                <div class="product-info">
                  <h3>{{ product.name }}</h3>
                  <p>{{ product.description }}</p>
                  <div class="price-stock">
                    <span class="product-price">￥{{ product.price.toFixed(2) }}</span>
                    <el-tag type="info">库存: {{ product.stock }}</el-tag>
                  </div>
                </div>

                <div class="quantity-actions">
                  <el-input-number
                      v-model="product.quantity"
                      :min="1"
                      :max="999"
                      size="small"
                  />
                  <el-button type="primary" size="small" @click="addToCart(product)">
                    加入购物车
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 分页器 -->
          <el-pagination
              v-if="recommendedProducts.length > 0"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="recommendedProducts.length"
              layout="prev, pager, next, jumper"
              @current-change="handlePageChange">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>

      <!-- 操作按钮 -->
      <el-row justify="center" class="action-buttons" :gutter="10">
        <el-col :span="4">
          <el-button v-if="role==='CUSTOMER'" type="success" @click="goToCart">去购物车</el-button>
        </el-col>
        <el-col :span="4">
          <el-button @click="goBack">返回</el-button>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

import { Product } from "../../types.ts";

type ProductItem = Product & { quantity: number };

export default defineComponent({
  name: 'ProductList',
  data() {
    return {
      products: [] as ProductItem[],
      recommendedProducts: [] as ProductItem[],  // 推荐商品数据
      searchQuery: '' as string,
      role: sessionStorage.getItem('userRole'),
      currentPage: 1,  // 当前分页页码
      pageSize: 6,     // 每页显示的推荐商品数量
      activeTab: 'all', // 默认显示"所有商品"标签
    };
  },
  computed: {
    filteredProducts(): ProductItem[] {
      const q = this.searchQuery.trim().toLowerCase();
      return this.products.filter(p => p.name.toLowerCase().includes(q));
    },
    // 获取分页后的推荐商品
    paginatedRecommendedProducts(): ProductItem[] {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.recommendedProducts.slice(start, end);
    },
  },
  created() {
    this.fetchProducts();
    // 只有消费者角色才加载推荐商品
    if (this.role === 'CUSTOMER') {
      this.fetchRecommendedProducts();
    }
  },
  methods: {
    async fetchProducts() {
      try {
        const resp = await axios.get<Product[]>('/api/product');
        this.products = resp.data.map(p => ({ ...p, quantity: 1 }));
      } catch (err) {
        console.error('获取商品数据失败:', err);
        ElMessage.error('加载产品失败，请稍后重试');
      }
    },
    async fetchRecommendedProducts() {
      try {
        const resp = await axios.get<Product[]>(`/api/product/recommend/${sessionStorage.getItem('userId')}`);
        this.recommendedProducts = resp.data.map(p => ({ ...p, quantity: 1 }));
      } catch (err) {
        console.error('获取推荐商品失败:', err);
        ElMessage.error('加载推荐商品失败，请稍后重试');
      }
    },
    addToCart(product: ProductItem) {
      const cartRaw = sessionStorage.getItem('cart') || '{}';
      const cart: Record<number, number> = JSON.parse(cartRaw);
      cart[product.id] = (cart[product.id] || 0) + product.quantity;
      sessionStorage.setItem('cart', JSON.stringify(cart));
      ElMessage.success(`${product.name} 已加入购物车`);
    },
    goToCart() {
      this.$router.push('/customer/cart');
    },
    goBack() {
      const role = sessionStorage.getItem('role');
      if (role === 'SELLER') this.$router.push('/seller');
      else if (role === 'CUSTOMER') this.$router.push('/customer');
      else if (role === 'ADMIN') this.$router.push('/admin');
    },
    handlePageChange(page: number) {
      this.currentPage = page;  // 更新当前分页页码
    },
    handleTabClick() {
      // 如果需要在标签切换时执行特定操作，可以在这里添加
    },
  },
});
</script>

<style scoped>
.product-list {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.products-list, .recommended-products {
  margin-top: 20px;
}

.product-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  margin-bottom: 20px;
}

.product-image {
  width: 100%;
  height: 180px;
  object-fit: contain;
  margin-bottom: 10px;
}

.product-info h3 {
  font-size: 1.1rem;
  margin: 5px 0;
}

.product-info p {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 10px;
  height: 40px;
  overflow: hidden;
}

.price-stock {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;
  margin-bottom: 10px;
}

.product-price {
  font-size: 1.2rem;
  font-weight: bold;
}

.quantity-actions {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.action-buttons {
  margin-top: 30px;
}

.el-pagination {
  margin-top: 20px;
}
</style>